<template>
  <div>
    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane label="未审核" name="unCheck">
        <custom-table
          :data="auditList"
          :columns="columns"
          :tableLoadingFlag="tableLoadingFlag"
          :operationColumn="operationColumn"
          :pagination="pagination">
        </custom-table>
      </el-tab-pane>
      <el-tab-pane label="已审核" name="alreadyCheck">
        <custom-table
          :data="alreadyAuditList"
          :columns="finishColumns"
          :tableLoadingFlag="finishTableLoadingFlag"
          :operationColumn="operationColumn1"
          :pagination="pagination1">
        </custom-table>
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="调拨审核" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form :model="auditDto" :rules="auditRules" label-width="60px" ref="auditForm">
        <el-form-item label="审核">
          <el-radio-group v-model.number="auditDto.approvedResult">
            <el-radio-button label="0">同意</el-radio-button>
            <el-radio-button label="1">不同意</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="原因" prop="cause">
          <el-input v-model.trim="auditDto.cause" placeholder="请输入原因"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="onBtnCancel()">取消</el-button>
        <el-button type="primary" @click="onBtnSubmit()" v-no-more-click>确定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="申请详情" center :visible.sync="applyDetailVisible" wdith="100%" :close-on-click-modal="false">
      <el-steps align-center :active="applyStep" finish-status="success" :process-status="processStatus">
        <el-step title="调拨申请">
        </el-step>
        <el-step title="审核"></el-step>
        <el-step title="审批"></el-step>
        <el-step title="发放"></el-step>
      </el-steps>
      <div v-if="applyStep>=1">
        <h4>审核结果：</h4>
        <custom-table
          :columns="columnDailogAudit"
          :data="applyAuditDetail"
          :tableLoadingFlag="tableLoadingFlag">
        </custom-table>
      </div>
      <div v-if="applyStep>=2">
        <h4>审批结果：</h4>
        <custom-table
          :columns="columnDailogApprove"
          :data="applyApproveDetail"
          :tableLoadingFlag="tableLoadingFlag">
        </custom-table>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { apiAllotSelfDetail } from '@/api/allot/apply'
  import CustomTable from '@/components/table/CustomTable'
  import { apiGetAuditList, apiAudit, aipGetAlreadyAuditList } from '@/api/allot/audit'
  import { getUserId, getUserName } from '@/utils/token'
  import { parseTime } from '@/utils'

  export default {
    components: {
      CustomTable
    },
    created () {
      let listQuery = {
        pageNumber: this.pagination.currentPage,
        pageSize: this.pagination.pageSize,
        userId: getUserId()
      }
      this.getAuditList(listQuery)
      this.getAlreadyAuditList(listQuery)
    },
    data () {
      return {
        activeName: 'unCheck',
        tableLoadingFlag: false,          // 审核列表
        columns: [
          {label: 'ID', name: 'id', width: '80', align: 'center'},
          {label: '申请单号', name: 'applicationNo', width: '150', align: 'center'},
          {label: '申请人', name: 'proposerName', width: '150', align: 'center'},
          {label: '调出省份', name: 'calloutProvince', width: '150', align: 'center'},
          {label: '调出方', name: 'calloutDepartment', width: '150', align: 'center'},
          {label: '接收省份', name: 'receiveProvince', width: '150', align: 'center'},
          {label: '接收方', name: 'receiveDepartment', width: '150', align: 'center'},
          {label: '接收人详细地址', name: 'receiverAddress', width: '250', align: 'center'},
          {label: '型号', name: 'modelName', width: '120', align: 'center'},
          {label: '数量', name: 'num', width: '80', align: 'center'},
          {label: '要求发出时间', name: 'requiredDate', width: '160', align: 'center', formatter: this.formatTime},
          {label: '备注', name: 'remark', align: 'center'}
        ],
        auditList: [],
        operationColumn: {
          width: '80',
          operations: [
            {name: '审核', callback: this.onBtnAudit}
          ]
        },
        finishTableLoadingFlag: false,
        finishColumns: [
          {label: '申请单号', name: 'applicationNo', width: '150', align: 'center'},
          {label: '申请时间', name: 'applicationDate', align: 'center', formatter: this.formatTime},
          {label: '申请人', name: 'proposerName', align: 'center'},
          {label: '调出省份', name: 'calloutProvince', width: '150', align: 'center'},
          {label: '调出方', name: 'calloutDepartment', width: '150', align: 'center'},
          {label: '接收省份', name: 'receiveProvince', width: '150',align: 'center'},
          {label: '接收方', name: 'receiveDepartment', width: '150',align: 'center'},
          {label: '接收人详细地址', name: 'receiverAddress', width: '250', align: 'center'},
          {label: '型号', name: 'modelName', width: '120', align: 'center'},
          {label: '数量', name: 'num', width: '80', align: 'center'},
          {label: '审核状态', name: 'applicationStatus', align: 'center'},
          {label: '备注', name: 'remark', align: 'center'}
        ],
        alreadyAuditList: [],
        // 表单操作栏
        operationColumn1: {
          width: '80',
          operations: [
            {name: '详情', callback: this.getDetailSelfApply}
          ]
        },
        // 表单列
        columnDailogAudit: [
          {label: '审核人', name: 'name', width: '100', align: 'center'},
          {label: '审核时间', name: 'time', width: '180', align: 'center',formatter: this.formatTime},
          {label: '审核结果', name: 'result', width: '150', align: 'center', formatter: this.formatStatus},
          {label: '原因', name: 'reason', align: 'center'}
        ],
        columnDailogApprove: [
          {label: '审批人', name: 'name', width: '100', align: 'center'},
          {label: '审批时间', name: 'time', width: '180', align: 'center',formatter: this.formatTime},
          {label: '审批结果', name: 'result', width: '150', align: 'center', formatter: this.formatStatus},
          {label: '原因', name: 'reason', align: 'center'}
        ],
        processStatus: 'wait',
        applyDetailVisible: false,
        applyStep: 0,
        applyAuditDetail: [
          {
            name: '',
            time: '',
            result: '',
            reason: ''
          }
        ],
        applyApproveDetail: [
          {
            name: '',
            time: '',
            result: '',
            reason: ''
          }
        ],
        dialogVisible: false,             // 审批模态框
        auditDto: {
          id: undefined,
          approverId: undefined,
          approverName: undefined,
          approvedResult: 1,
          cause: ''
        },
        auditRules: {
          cause: [
            {
              validator: (rule, value, callback) => {
                if (this.auditDto.approvedResult === 1 && value === '') {
                  callback(new Error('请输入不同意原因'))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            },
            {max: 255, message: '长度不得超过255字符', trigger: 'blur'}
          ]
        },
        pagination: this.getData(this.getAuditList),
        pagination1: this.getData(this.getAlreadyAuditList)
      }
    },
    methods: {
      getAuditList (listQuery) {
        this.tableLoadingFlag = true
        apiGetAuditList(listQuery).then(response => {
          this.auditList = response.data
          this.pagination.totalRecords = response.totalRecords
          this.tableLoadingFlag = false
        }).catch(() => {
          this.tableLoadingFlag = false
        })
      },
      getAlreadyAuditList (listQuery) {
        this.finishTableLoadingFlag = true
        aipGetAlreadyAuditList(listQuery).then(response => {
          this.alreadyAuditList = response.data
          this.pagination1.totalRecords = response.totalRecords
          this.finishTableLoadingFlag = false
        }).catch(() => {
          this.finishTableLoadingFlag = false
        })
      },
      getDetailSelfApply (row) {
        apiAllotSelfDetail(row.id).then(response => {
          if (response.data.applicationStatus === 1) {
            // 已提交申请，待审核
            this.applyStep = 0
            this.processStatus = 'success'
          } else if (response.data.applicationStatus === 5) {
            // 设备已全部发放
            this.applyStep = 3
            this.processStatus = 'success'
          } else if (response.data.applicationStatus === 2) {
            // 已通过审核，待审批
            this.applyStep = 1
            this.processStatus = 'success'
          } else if (response.data.applicationStatus === 3 || response.data.applicationStatus === 4) {
            // 已通过审批，待发放
            this.applyStep = 2
            this.processStatus = 'success'
          } else if (response.data.applicationStatus === 6 && (response.approve === undefined || response.approve === null)) {
            // 未通过审核
            this.applyStep = 1
            this.processStatus = 'error'
          } else if (response.data.applicationStatus === 6 && response.approve !== undefined && response.approve !== null) {
            // 未通过审批
            this.applyStep = 2
            this.processStatus = 'error'
          }
          if (this.applyStep >= 1) {
            this.applyAuditDetail[0].name = response.audit.name
            this.applyAuditDetail[0].time = response.audit.approveDate
            this.applyAuditDetail[0].result = response.audit.result
            this.applyAuditDetail[0].reason = response.audit.cause
          }
          if (this.applyStep >= 2) {
            this.applyApproveDetail[0].name = response.approve.name
            this.applyApproveDetail[0].time = response.approve.approveDate
            this.applyApproveDetail[0].result = response.approve.result
            this.applyApproveDetail[0].reason = response.approve.cause
          }
          this.applyDetailVisible = true
        })
      },
      formatStatus (row, column, cellValue) {
        if (cellValue === 1) {
          return '不通过'
        }
        return '通过'
      },
      onBtnAudit (row) { // 审核按钮事件,弹出审核对话框
        let dto = this.auditDto
        dto.approvedResult = 1
        dto.applicationId = row.id
        dto.approverId = getUserId()
        dto.approverName = getUserName()
        this.dialogVisible = true
      },
      onBtnSubmit () {      // 审核模态框中确定按钮事件
        this.$refs['auditForm'].validate((valid) => {
          if (valid) {
            // 审核接口
            apiAudit(this.auditDto).then(() => {
              this.$message({
                showClose: true,
                message: '审核成功！',
                type: 'success'
              })
              this.getAuditList()
              this.onBtnCancel()
            })
          } else {
            return false
          }
        })
      },
      onBtnCancel () {     // 审核模态框中取消按钮事件
        this.dialogVisible = false
        this.$refs['auditForm'].resetFields()
      },
      formatTime (row, column, cellValue) {
        if (column.property === 'requiredDate') {
          return parseTime(cellValue, '{y}-{m}-{d}')
        } else {
          return parseTime(cellValue)
        }
      }
    }
  }
</script>
